package com.hxd.otc.module.order.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.BaseMvpDialogFragment;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.BankType;
import com.hxd.otc.common.enums.CardLevelEnum;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.dialog.OrderPaymentMethodPopupWindow;
import com.hxd.otc.module.my.activity.BankCardActivity;
import com.hxd.otc.module.my.activity.SecurityCenterActivity;
import com.hxd.otc.module.my.bean.BankCardBean;
import com.hxd.otc.module.order.contract.OrderConfirmPaymentContract;
import com.hxd.otc.module.order.presenter.OrderConfirmPaymentPresenter;
import com.hxd.otc.other.CustomBounceTopEnter;
import com.hxd.otc.other.SlideTopExit;
import com.hxd.otc.utils.LogUtils;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.StringUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

import static com.hxd.otc.dialog.OrderPaymentMethodPopupWindow.BANK_TYPE_WRITE;

/**
 * Created by lzy on 2019/1/18 0018.
 * description ${确认付款DialogFragment}
 */
public class ConfirmPaymentDialogFragment extends BaseMvpDialogFragment<OrderConfirmPaymentPresenter> implements OrderConfirmPaymentContract.IView {
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_content)
    TextView mTvContent;
    @BindView(R.id.tv_payment_account_number)
    TextView mTvPaymentAccountNumber;
    @BindView(R.id.et_account)
    EditText mEtAccount;
    @BindView(R.id.iv_more)
    ImageView mIvMore;
    @BindView(R.id.tv_cancel)
    TextView mTvCancel;
    @BindView(R.id.tv_confirm)
    TextView mTvConfirm;
    MultipleBlocksDialog bindBankCardDialog;
    String realName;

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_fragment_confirm_payment;
    }

    @Override
    protected OrderConfirmPaymentPresenter createPresenter() {
        return new OrderConfirmPaymentPresenter(this);
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        mPresenter.requestBankCardList(false);
    }

    @Override
    public void onStart() {
        super.onStart();
        Window win = getDialog().getWindow();
        // 一定要设置Background，如果不设置，window属性设置无效
        win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);

        WindowManager.LayoutParams params = win.getAttributes();
        params.gravity = Gravity.CENTER;
        // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.MATCH_PARENT;
        win.setAttributes(params);
        getDialog().setCanceledOnTouchOutside(false);
    }

    @OnClick({R.id.iv_more, R.id.tv_cancel, R.id.tv_confirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_more:
                showSelectPaymentMethodPopupWindow();
                break;
            case R.id.tv_cancel:
                dismiss();
                break;
            case R.id.tv_confirm:
                onConfirm();
                break;
        }
    }

    String supportPayId;

    private void onConfirm() {

        BankCardBean selBankCardBean = mPresenter.getSelBankCardBean();
        if (selBankCardBean == null) {
            showToast(getString(R.string.please_select_payment_method_or_manually_enter_payment_account_and_payment_name));
            return;
        }
//        confirmPaymentName  付款账号名称
//        confirmPaymentAccount  付款账号信息

        String confirmPaymentName = realName;//付款账号名称

        if (TextUtils.isEmpty(confirmPaymentName)) {
            showToast(getString(R.string.please_enter_payment_name_and_payment_account_number));
            return;
        }

        if (!UserHelper.isSilver() && !UserHelper.isMerchant()
                && (selBankCardBean.getType() == 3 || selBankCardBean.getType() == BANK_TYPE_WRITE)) {//
            if (!confirmPaymentName.equals(UserHelper.getRealName())) {
                showToast(getString(R.string.real_name_and_name_not_complay));
                return;
            }
        }

        if (mOnPayAccountInfoListener != null) {
            mOnPayAccountInfoListener.onPayAccountInfo(confirmPaymentName, supportPayId);
        }
        dismiss();
    }

    private OrderPaymentMethodPopupWindow mPaymentMethodPopupWindow;

    private void showSelectPaymentMethodPopupWindow() {

        ArrayList<BankCardBean> bankCardList = mPresenter.getBankCardList();
        if (bankCardList == null) return;

        if (mPaymentMethodPopupWindow == null) {
            mPaymentMethodPopupWindow = new OrderPaymentMethodPopupWindow(getContext());
            mPaymentMethodPopupWindow.offset(0, 0)
                    .setOnSelPayMethodListener(new OrderPaymentMethodPopupWindow.OnSelPayMethodListener() {
                        @Override
                        public void onSelPayMethod(BankCardBean bankCardBean) {
                            updateSelBankCard(bankCardBean);
                        }
                    })
                    .setWidth(mEtAccount.getWidth())
                    .gravity(Gravity.BOTTOM)
                    .showAnim(new CustomBounceTopEnter())
                    .dismissAnim(new SlideTopExit())
                    .setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            if (mIvMore != null) {
                                mIvMore.setSelected(false);
                            }
                        }
                    });
        }
        mPaymentMethodPopupWindow
                .anchorView(mEtAccount)
                .setSelItem(mPresenter.getSelBankCardBean())
                .setData(bankCardList);
        mPaymentMethodPopupWindow.show();
        mIvMore.setSelected(true);
    }

    public void updateSelBankCard(BankCardBean bankCardBean) {
        LogUtils.e("updateSelBankCard===1===" + bankCardBean.toString());
        mPresenter.setSelBankCard(bankCardBean);
        mEtAccount.setCompoundDrawablesWithIntrinsicBounds(
                bankCardBean.getType() == BANK_TYPE_WRITE ?
                        null :
                        ResourceUtil.getDrawable(BankType.getBankTypeByValue(bankCardBean.getType()).getSelectPaymentMethodLogo()),
                null, null, null);
        switch (bankCardBean.getType()) {//1微信2支付宝3银行卡
            case 1:
                mEtAccount.setText(R.string.weixin);
                mEtAccount.setHint(R.string.select_the_added_collection_method);
                mEtAccount.setEnabled(false);
                supportPayId = bankCardBean.getId();
                realName = bankCardBean.getRealName().trim();
                break;
            case 2:
                mEtAccount.setText(R.string.alipay);
                mEtAccount.setHint(R.string.select_the_added_collection_method);
                mEtAccount.setEnabled(false);
                supportPayId = bankCardBean.getId();
                realName = bankCardBean.getRealName().trim();
                break;
            case 3:
                String payNo = StringUtil.emptyIfNull(bankCardBean.getPayNo());
                mEtAccount.setText(String.format("%s(%s)", StringUtil.emptyIfNull(bankCardBean.getBankName()), payNo.length() > 4
                        ? payNo.substring(payNo.length() - 4) : payNo));
                mEtAccount.setHint(R.string.select_the_added_collection_method);
                mEtAccount.setEnabled(false);
                supportPayId = bankCardBean.getId();
                realName = bankCardBean.getRealName().trim();
                break;
            default:
//                mEtAccount.setHint(getString(R.string.enter_payment_name_and_payment_account_number));
//                mEtAccount.setText("");
//                mEtAccount.setEnabled(true);

                if (UserHelper.getCardLevel().equals(CardLevelEnum.LEVEL_0)) {
                    if (bindBankCardDialog == null) {
                        bindBankCardDialog = new MultipleBlocksDialog(getContext());
                        bindBankCardDialog
                                .setTitlewithOutPading(getContext().getString(R.string.only_real_name_auth_can_bind_card))
                                .setTvSure(getContext().getString(R.string.go_to_real_name_auth), new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        bindBankCardDialog.dismiss();
                                        Intent intent = new Intent(getContext(), SecurityCenterActivity.class);
                                        getContext().startActivity(intent);
                                    }
                                });
                    }
                    bindBankCardDialog.show();
                } else {
                    Intent intent = new Intent(getContext(), BankCardActivity.class);
                    startActivityForResult(intent, 123);
                }
                break;
        }
    }

    public static ConfirmPaymentDialogFragment getInstance() {
        return new ConfirmPaymentDialogFragment();
    }

    @Override
    public void requestBankCardListSuccess(boolean isInitiative) {
        if (isInitiative) {
            showSelectPaymentMethodPopupWindow();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {
            mPresenter.requestBankCardList(false);
        }
    }

    private OnPayAccountInfoListener mOnPayAccountInfoListener;

    public ConfirmPaymentDialogFragment setOnPayAccountInfoListener(OnPayAccountInfoListener onPayAccountInfoListener) {
        mOnPayAccountInfoListener = onPayAccountInfoListener;
        return this;
    }

    public interface OnPayAccountInfoListener {
        void onPayAccountInfo(String confirmPaymentName, String supportPay);
    }
}
